//
//  FPDFDocument.m
//  Foundation
//
//  Created by 吴新庭 on 2019/8/29.
//

#import "FPDFDocument.h"

@interface FPDFDocument ()

@property (nonatomic, assign) CGPDFDocumentRef document;
@property (nonatomic, assign) NSInteger pageCount;


@end

@implementation FPDFDocument

+ (FPDFDocument *)pdfForPath:(NSString *)path {
    FPDFDocument *info = [[FPDFDocument alloc] init];
    info.path = path;
    return info;
}

- (void)setPath:(NSString * _Nonnull)filename {
    _path = filename;
    
    if (self.document != NULL) {
        CGPDFDocumentRelease(self.document);
        self.document = NULL;
    }
    
    CFStringRef path;
    CFURLRef url;
    
    path = CFStringCreateWithCString (NULL, [filename UTF8String], kCFStringEncodingUTF8);
    url = CFURLCreateWithFileSystemPath (NULL, path, kCFURLPOSIXPathStyle, 0);
    
    CFRelease (path);
    self.document = CGPDFDocumentCreateWithURL (url);
    CFRelease(url);
    self.pageCount = CGPDFDocumentGetNumberOfPages (self.document);
    
    NSMutableArray *mArr = [NSMutableArray array];
    for (NSInteger i = 1; i <= self.pageCount; i++) {
        FPDFPage *page = [[FPDFPage alloc] initWithPage:CGPDFDocumentGetPage(self.document, i)];
        page.index = i;
        [mArr addObject:page];
    }
    _pages = mArr;
}

- (void)dealloc {
    if (self.document != NULL) {
        CGPDFDocumentRelease(self.document);
        self.document = NULL;
    }
}

@end
